package com.g8.pethospitallearnbackend.service.impls;

import com.g8.pethospitallearnbackend.exception.CustomException;
import com.g8.pethospitallearnbackend.service.FileUploadService;
import com.g8.pethospitallearnbackend.utils.responseUtil.ResponseStatusEnum;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Override
    public List<String> uploadImageAndVideo(List<MultipartFile> files) {
        String UPLOAD_DIR = "/root/pethospital/resources/";
//        String UPLOAD_DIR = "D:\\";//本地测试
        if (files.isEmpty()) {
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"请上传文件");
        }
        List<String> mediaUrl=new ArrayList<>();

        try {
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    //获得文件类型
                    /*不知道为什么contenttype不行，后来用后缀判断
                    对于图片文件（例如.jpg、.png、.gif等）：image/jpeg、image/png、image/gif等。
                    对于视频文件（例如.mp4、.avi、.mov等）：video/mp4、video/x-msvideo、video/quicktime等。
                    对于文档文件（例如.docx、.pdf、.txt等）：application/msword、application/pdf、text/plain等。
                     */
                    String contentType = file.getContentType();
                    String originalFilename = file.getOriginalFilename();//原始文件名

                    //验证是否是图片/视频
                    if (isValidFileType(originalFilename)) {
                        // 生成唯一标识文件名
                        String extension = originalFilename.substring(originalFilename.lastIndexOf('.'));//获取后缀
                        String newFilename = UUID.randomUUID() + extension;
                        //写文件
                        byte[] bytes = file.getBytes();
                        Path path = Paths.get(UPLOAD_DIR + newFilename);
                        Files.write(path, bytes);
                        mediaUrl.add(fileNameToUrl(newFilename));
                    } else {
                        throw new CustomException(ResponseStatusEnum.BAD_REQUEST,originalFilename+"文件类型不合法"+contentType);
                    }
                }
            }
            return mediaUrl;
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(ResponseStatusEnum.BAD_REQUEST,"上传文件失败");
        }
    }

    private boolean isValidFileType(String fileName) {
        // Example: validate image files
        String[] validExtensions={".jpg", ".jpeg", ".png", ".gif", ".bmp",".mp4", ".avi", ".mov", ".mkv", ".flv", ".wmv"};
        String lowerCaseFileName=fileName.toLowerCase();
        for (String extension : validExtensions) {
            if (lowerCaseFileName.endsWith(extension)) {
                return true;
            }
        }
        return false;
    }

    //转换成可以访问的url地址
    private String fileNameToUrl(String fileName){
        return "http://47.120.60.166:7070/resources/"+fileName;
    }
}
